package com.example.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class FileController {

    // 配置允许访问的根目录（根据实际情况修改）
    private final Path rootPath = Paths.get("C:\\project").toAbsolutePath();

    @GetMapping("/api/file/preview")
    public ResponseEntity<Resource> previewFile(
            @RequestParam String path,
            HttpServletRequest request) throws IOException {

        // 1. 路径安全校验
        Path filePath = rootPath.resolve(path).normalize();
        if (!filePath.startsWith(rootPath)) {
            throw new AccessDeniedException("非法路径访问");
        }

        // 2. 读取文件资源
        Resource resource = new UrlResource(filePath.toUri());

        // 3. 校验文件存在性
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        // 4. 设置Content-Type
        String contentType = request.getServletContext()
                .getMimeType(resource.getFile().getAbsolutePath());

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .body(resource);
    }
}
